package com.kk.springcloud.controller;

import com.kk.entities.CommResult;
import com.kk.entities.Payment;
import com.kk.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/create")
    public CommResult<Payment> create(Payment payment) {
        int i = paymentService.create(payment);
        if (i == 1) {
            return new CommResult<>(200, "添加payment成功.", payment);
        }
        return new CommResult<>(444, "添加payment失败.");
    }

    @GetMapping("/get/{id}")
    public CommResult<Payment> getPaymentById(@PathVariable("id") Integer id) {
        Payment paymentById = paymentService.getPaymentById(id);
        if (paymentById != null) {
            return new CommResult<>(200, "根据id获取payment成功.", paymentById);
        }
        return new CommResult<>(444, "根据id获取payment失败.");
    }

    @GetMapping("/discover")
    public Object discover() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service: ===>" + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            System.out.println("instance.getInstanceId() = " + instance.getInstanceId());
            System.out.println("instance.getHost() = " + instance.getHost());
            System.out.println("instance.getPort() = " + instance.getPort());
            System.out.println("instance.getMetadata() = " + instance.getMetadata());
            System.out.println("instance.getScheme() = " + instance.getScheme());
            System.out.println("instance.getServiceId() = " + instance.getServiceId());
            System.out.println("instance.getUri() = " + instance.getUri());
        }
        return this.discoveryClient;
    }


    @GetMapping("/payment/feign")
    public String feign() {
        log.info("server port is " + serverPort);
        return "feign : " + serverPort;
    }
}
